package network.client;


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class NetworkClient extends JFrame implements ActionListener, KeyListener {

    Socket kkSocket;
    PrintWriter out;
    ObjectInputStream in;
    String fromServer;
    Map<String, String[][]> fromServer2;
    String fromUser;
    
    Timemachine tm = Timemachine.getInstance();
        
    JLabel fehler;
    
    Container cP;
    JPanel main;
    JTextField username;
    JPasswordField password;
    JButton send;
    
    JMenuBar menuLeiste;
    JMenu znb;
    JMenu hilfe;
    JMenuItem untermenu1;
    JMenuItem untermenu2;
    JMenuItem untermenu3;
    JMenuItem untermenu4;
    JLabel username2;
    JLabel password2;
    JLabel nichts;
    JPanel main1;
    JPanel main2;
    JLabel oben;
    JLabel rechts;
    JLabel unten;
    JLabel links;
    JPanel main3;
    public NetworkClient() throws IOException {


        //GUI bauen
        this.setSize(400, 220);
        this.setResizable(false);
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
        username = new JTextField();
        username.setPreferredSize(new Dimension(200, 10));

        password = new JPasswordField();
        password.setPreferredSize(new Dimension(200, 10));

        username2 = new JLabel();
        username2.setText("Username: ");
        username2.setHorizontalAlignment(username2.CENTER);
        username2.setPreferredSize(new Dimension(200, 20));

        password2 = new JLabel();
        password2.setText("Passwort: ");
        password2.setHorizontalAlignment(password2.CENTER);
        password2.setPreferredSize(new Dimension(200, 20));

        nichts = new JLabel();
        nichts.setPreferredSize(new Dimension(200, 20));
        
        oben = new JLabel();
        oben.setPreferredSize(new Dimension(50, 50));
        
        rechts = new JLabel();
        rechts.setPreferredSize(new Dimension(50, 10));
        
        unten = new JLabel();
        unten.setPreferredSize(new Dimension(50, 50));
        
        links = new JLabel();
        links.setPreferredSize(new Dimension(0, 10));


        send = new JButton("send");
        
        send.addActionListener(this);
        

        
        nichts.setPreferredSize(new Dimension(100, 20));
        send.setPreferredSize(new Dimension(50, 20));

        main1 = new JPanel();
        main1.add(username);
        main1.add(password);
        main1.add(send);
        
        main1.setLayout(new GridLayout(3, 1, 0, 10));
        main1.setBackground(new Color(0,191,255));
  
        
        
        main2 = new JPanel();
        main2.add(username2);
        main2.add(password2);
        main2.add(nichts);
        main2.setLayout(new GridLayout(3, 1, 0, 10));
        main2.setBackground(new Color(0,191,255));

        
        main3 = new JPanel();
        main3.setLayout(new BorderLayout());
        main3.add(main1, BorderLayout.EAST);
        main3.add(main2, BorderLayout.WEST);
        main3.setBackground(new Color(0,191,255));
        getRootPane().setDefaultButton(send);


//        main4 = new JPanel();
        cP = this.getContentPane();
        cP.setLayout(new BorderLayout());
        cP.add(oben, BorderLayout.NORTH);
        cP.add(rechts, BorderLayout.EAST);
        cP.add(unten, BorderLayout.SOUTH);
        cP.add(links, BorderLayout.WEST);
        cP.add(main3, BorderLayout.CENTER);
        cP.setBackground(new Color(0,191,255));

                


//        cP = this.getContentPane();
//        cP.setLayout(new BorderLayout());
//        cP.add(main1, BorderLayout.EAST);
//        cP.add(main2, BorderLayout.WEST);
//        getRootPane().setDefaultButton(send);
        this.setTitle("Batcher");
        setVisible(true);


        try {
            kkSocket = new Socket("172.16.2.60", 15387);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            //in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            in = new ObjectInputStream( kkSocket.getInputStream() );
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host");
            System.exit(1);
        } catch (IOException e) {
            fehler = new JLabel();
            fehler.setText("Verbindung zum Server fehlgeschlagen");
            fehler.setHorizontalAlignment(JLabel.CENTER);
            fehler.setForeground(Color.red);
            fehler.setPreferredSize(new Dimension(150, 20));
            cP.add(fehler, BorderLayout.NORTH);
            this.validate();
        }
        try {
            fromServer = (String) in.readObject();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    
    public void rebuildGUI(String[][] dataarray, String[] timeplanarray, String month){
        cP.removeAll();
        
        int days = dataarray.length;
        int maxtimestamps = dataarray[0].length-1;
        
        JPanel timetable = new JPanel(new GridLayout(maxtimestamps+3,days));
        
        for (int i=0; i<days; i++){
            JLabel tmp;
            if (dataarray[i][0].equals("null")){
                tmp = new JLabel();
            } else {
                tmp = new JLabel(dataarray[i][0]);
            }
            tmp.setBorder(new LineBorder(Color.yellow, 5));
            timetable.add(tmp);
        }
        
        for (int i=1; i<maxtimestamps+1; i++){
            for (int j=0; j<days; j++){
                JLabel tmp = new JLabel(dataarray[j][i]);
                tmp.setBorder(new LineBorder(Color.yellow, 5));
                timetable.add(tmp);
            }
        }
        
        
        String[] worktimes = new String[days];
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        for (int i=0; i<days; i++){
            Date worktime = new Date(0);
            for (int j=0; j<maxtimestamps; j+=2){
                try {
                    Date time1 = sdf.parse(dataarray[i][j+1]);
                    Date time2 = sdf.parse(dataarray[i][j+2]);
                    worktime = new Date(worktime.getTime()+time2.getTime()-time1.getTime());
                } catch (ParseException | NullPointerException ex) {
                }
            }
            worktime = new Date(worktime.getTime()-1000*60*60);
            worktimes [i] = sdf.format(worktime);
        }
        
        for (int i=0; i<days; i++){
            JLabel tmp;
            tmp = new JLabel(worktimes[i]);
            tmp.setBorder(new LineBorder(Color.blue, 5));
            timetable.add(tmp);
        }
        int firstweekday = -1;
        try {
            firstweekday = tm.getWeekdayAsInt("dd.MM.yyyy", "01."+month);
        } catch (ParseException ex) {
            Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        int d = firstweekday;
        for (int i=0; i<days; i++){
            JLabel tmp;
            tmp = new JLabel(timeplanarray[d]);
            System.out.println(d);
            tmp.setBorder(new LineBorder(Color.black, 5));
            timetable.add(tmp);
            if (d>5){
                d=0;
            } else {
                d++;
            }
        }
    
        
        JScrollPane timetablescroller = new JScrollPane(timetable);
        
        setSize(1400, 600);

        cP.setLayout(new BorderLayout());
        menuLeiste = new JMenuBar();
        znb = new JMenu("ZNB");
        hilfe = new JMenu("Hilfe");
        untermenu1 = new JMenuItem("Ü1");
        untermenu2 = new JMenuItem("U2");

        menuLeiste.add(znb);
        menuLeiste.add(hilfe);
        
        znb.add(untermenu1);

        hilfe.add(untermenu2);

        znb.addActionListener(this);
        hilfe.addActionListener(this);
        
        cP.add(menuLeiste, BorderLayout.NORTH);
        cP.add(timetablescroller, BorderLayout.CENTER);
        
        this.validate();


    }

    public static void main(String[] args) throws IOException {
        NetworkClient client = new NetworkClient();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == send) {
            try {
                out.println(username.getText() + "|" + new MD5().md5(password.getText()));
            } catch (Exception ex) {
                Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                try {
                    fromServer = (String) in.readObject();
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (IOException ex) {
                Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (fromServer.equals("loginsuccess")){
                String month = tm.formatDate("MM.yyyy");
                try {
                    out.println("requestdata");
                    try {
                        fromServer = (String) in.readObject();
                        out.println(month);
                        fromServer2 = (HashMap<String, String[][]>) in.readObject();
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                } catch (IOException ex) {
                    Logger.getLogger(NetworkClient.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                String[] timeplanarray = fromServer2.get("timeplan")[0];
                String[][] dataarray = fromServer2.get("times");
                
                
                rebuildGUI(dataarray, timeplanarray, month);
            } else {
                fehler = new JLabel();
                fehler.setText("Username oder Passwort nicht korrekt");
                fehler.setHorizontalAlignment(JLabel.CENTER);
                fehler.setForeground(Color.red);
                fehler.setPreferredSize(new Dimension(150, 20));
                cP.add(fehler, BorderLayout.NORTH);
                this.validate();
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
}